package com.infoclue.modules.km.utils;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.jeecg.modules.KM.entity.KmDoc;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Pattern;

/**
 * @Author wt
 * @Date: 2024/7/2 15:00
 * @Description:
 */
@Service
@Slf4j
public class EmbeddingUtil {


    @Value("${jeecg.path.upload}")
    private String upLoadPath;

    @Value("${jeecg.path.upload}")
    private String maxkbserver;

    @Value("${jeecg.maxkb.maxkb_url}")
    private String maxkbUrl;

    @Value("${jeecg.maxkb.maxkb_username}")
    private String maxkbusername;

    @Value("${jeecg.maxkb.maxkb_userpass}")
    private String maxkbuserpass;

    @Value("${jeecg.maxkb.maxkb_userid}")
    private String maxkbuserid;

    private static final Pattern ILLEGAL_JSON_CHAR_PATTERN = Pattern.compile("[^\\p{Cntrl}\\p{Digit}\\p{L}\\p{Punct}\\p{Space}]");

    public static String filterIllegalJsonChars(String input) {
        return ILLEGAL_JSON_CHAR_PATTERN.matcher(input).replaceAll("");
    }

    public static String trimControlCharacter(String str) {
        return str == null ? null : str.replaceAll("\\p{Cntrl}", " ");
    }

    public static void main1(String[] args)  {
        //WebService的发布地址
        String address = "http://10.188.9.223:9088/WebService/ServiceHello";

//        ComUtil.Initialize();
//        Endpoint.publish(address, new ServiceHello());
        //System.out.println("调用成功。");
        System.out.println("使用WebServicePublishServlet发布webservice成功!");

    }
    public static void main(String[] args) {


        Date now = new Date();

        System.out.println(now);

//Wed Jan 31 23:32:03 GMT+08:00 2018


//例如我的环境时区为：(UTC+08:00)北京，重庆，香港特别行政区，乌鲁木齐（+0800）

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");

        System.out.println(sdf.getTimeZone());

        System.out.println(sdf.format(now));
    }


    /**
     * 登录并获取Token。
     *
     * @param username 用户名
     * @param password 密码
     * @return Token字符串，如果请求失败或响应不包含token，则返回null
     * @throws IOException 如果网络请求过程中发生I/O错误
     */
    public static String loginAndGetToken(String username, String password, String ipAddress) throws IOException {
        String loginEndpoint = ipAddress + "/api/user/login";
        // 创建URL对象
        URL url = new URL(loginEndpoint);
        log.info("========url===========" + url.openConnection());
        // 打开连接
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        try {
            // 设置请求方法
            connection.setRequestMethod("POST");
            // 设置请求头信息
            connection.setRequestProperty("Cache-Control", "no-cache");
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestProperty("Postman-Token", "<calculated when request is sent>");
            connection.setRequestProperty("Accept", "application/json");
            connection.setRequestProperty("Content-Length", "<calculated when request is sent>");
            connection.setRequestProperty("Host", "<calculated when request is sent>");
            connection.setRequestProperty("User-Agent", "PostmanRuntime/7.37.3");
            connection.setRequestProperty("Accept", "*/*");
            connection.setRequestProperty("Accept-Encoding", "gzip, deflate, br");
            connection.setRequestProperty("Connection", "keep-alive");
            connection.setRequestProperty("AUTHORIZATION", "eyJ1c2VybmFtZSI6ImFkbWluIiwiaWQiOiJmMGRkOGY3MS1lNGVlLTExZWUtOGM4NC1hOGExNTk1ODAxYWIiLCJlbWFpbCI6IiIsInR5cGUiOiJVU0VSIn0:1sJOCV:E97DN1fdd6_-Mb92br3Ro0LMJqnyDFYepgtH05zfOCI");
            connection.setRequestProperty("Accept", "application/json, text/plain, */*");
            connection.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.9,zh-TW;q=0.8,en-US;q=0.7,en;q=0.6");
            connection.setRequestProperty("Connection", "keep-alive");
            connection.setRequestProperty("Cookie", "Webstorm-5f995900=190abac4-9716-4b69-bf43-2dc82bd94ab1; sb-localhost-auth-token-code-verifier=%223f610884a20b6a33f8bd70367a1029db93cb97e9c2f6ada17a0574b19c0ef6ee59662ad3f57ded9533598849efe9101ea647f8b34c103bf1%2FPASSWORD_RECOVERY%22; __stripe_mid=5cc94e4f-33cf-4907-a470-4ed6a296cf2dedc790; _ga=GA1.1.1614442558.1715241741; _ga_FVWC4GKEYS=GS1.1.1715403475.2.0.1715403475.0.0.0; jenkins-timestamper-offset=-28800000; session=.eJzllV1vokAUhv8LSb1pV2b4HEzMxqpIFa1fVdcbwsIgtCODMCrY9L93dE23a1j_gMlJhswZ5rx5not5F5yMuQw7NPI9R1ma7fEePufxr8ehOc5bRqgZbfqqHxaB-yjU3gXfZe5xjWnsYaEmzMI2Djr2gKBZv7lsxdZ0uhAehBT7UYo95mzTiJ8KGUtqokio55KQZqymAgBEd8tCmkYHzH_YpuTvOQiqvAytqik1BAwgptgl60xcF6cPMUkpox4lIk1wHPk_PBrHfNjpwp8pzhIaZ9hhRYLrHvVxxSMRjpkT-fWAuNmb4yYJrHyPWD8OvpMbd5LJ6ysm3zkG5VtfUSuZx4fW_wy-x2s3Ivc8ThAR3jqCrF9nWDmBq5di-3gQcJ4INahDpEkQqEpVRggpCPHOd029fCu_5szcWPaIPc46O9vUlabU8PdJZxGWacK24b-xebE24cZqD6Ni0mjftqbrDM-aSrH9o4mXDqqyJgNZubAUFGZXW74EvjSddy0TIgQ6-CUem5I-syZlloi6lMe7mdrMgg2aZrlsacVtW7rO8GypFNulJQVUVYhkAC8shf15BKe73_1JZ7ts9A-qNkfj1Bj0dFntd8ssZfZuDCyjiZOktZXxKngCxm1bus7wbKkU26UlzgDoSFGhcaEpHuI5CNFgMNn5huQeJquoG1j5fLg6LHelLxPojZ6e2chctQ6uPV3ti4kS3Lam6wzPmkqxXWhCEqxCzZChxBsxztl_QYaYECp8fAJw6NRo.ZnAFbg.Sl3BiGaOylYh6J9vLOu5Ep788f4");
            connection.setRequestProperty("Origin", "http://localhost:3000");
            connection.setRequestProperty("Referer", "http://localhost:3000/ui/login");
            connection.setRequestProperty("Sec-Fetch-Dest", "empty");
            connection.setRequestProperty("Sec-Fetch-Mode", "cors");
            connection.setRequestProperty("Sec-Fetch-Site", "same-origin");
            connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36");
            connection.setRequestProperty("sec-ch-ua", "\"Google Chrome\";v=\"125\", \"Chromium\";v=\"125\", \"Not.A/Brand\";v=\"24\"");
            connection.setRequestProperty("sec-ch-ua-mobile", "?0");
            connection.setRequestProperty("sec-ch-ua-platform", "\"macOS\"");
            // 发送POST请求必须设置
            connection.setDoOutput(true);

            // 创建请求体
            String urlParameters = "username=" + URLEncoder.encode(username, StandardCharsets.UTF_8.name())
                    + "&password=" + URLEncoder.encode(password, StandardCharsets.UTF_8.name());

            log.info("====urlParameters=====" + urlParameters);
            // 获取输出流并写入请求体
            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = urlParameters.getBytes(StandardCharsets.UTF_8);
                os.write(input, 0, input.length);
            }

            // 读取响应码
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // 使用BufferedReader读取响应
                try (BufferedReader reader = new BufferedReader(
                        new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }
                    log.info("===response===" + response);
                    // 将响应转换为JSON字符串
                    String jsonResponse = response.toString();
                    log.info("===response.toString()===" + new org.json.JSONObject(jsonResponse).optString("data", null));
                    // 假设响应体是一个JSON对象，包含token字段
                    // 使用适当的JSON库解析JSON字符串并获取token
                    // 这里使用org.json库作为示例
                    return new org.json.JSONObject(jsonResponse).optString("data", null);
                }
            } else {
                log.info("===处理错误响应=====" + responseCode);
                // 处理错误响应
                throw new IOException("Login failed with HTTP status: " + responseCode);
            }
        } finally {
            // 关闭连接
            if (connection != null)
                connection.disconnect();
        }
    }

    /**
     * logout
     *
     * @return Token字符串，如果请求失败或响应不包含token，则返回null
     * @throws IOException 如果网络请求过程中发生I/O错误
     */
    public static String logoutToken(String token, String ipAddress) throws IOException {
        String loginEndpoint = ipAddress + "/api/user/logout";
        // 创建URL对象
        URL url = new URL(loginEndpoint);
        log.info("===========logoutToken==========" + url.openConnection());
        // 打开连接
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        try {
            // 设置请求方法
            connection.setRequestMethod("POST");
            // 设置请求头信息值
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("Accept", "*/*");
            connection.setRequestProperty("AUTHORIZATION",token);
            // 发送POST请求必须设置
            connection.setDoOutput(true);

                // 读取响应码
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // 使用BufferedReader读取响应
                try (BufferedReader reader = new BufferedReader(
                        new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }
                    // 将响应转换为JSON字符串
                    String jsonResponse = response.toString();
                    log.info("===响应=====" + new org.json.JSONObject(jsonResponse).optString("data", null));
                    // 这里使用org.json库作为示例
                    return new org.json.JSONObject(jsonResponse).optString("data", null);
                }
            } else {
                log.info("===处理错误响应=====" + responseCode);
                // 处理错误响应
                throw new IOException("Login failed with HTTP status: " + responseCode);
            }
        } finally {
            // 关闭连接
            if (connection != null)
                connection.disconnect();
        }
    }


    /**
     * @description 校验字符串是否是 json 格式
     */
    public static boolean isJson(String json) {
        if(StringUtils.isBlank(json)){
            return false;
        }
        boolean isJsonObject = true;
        boolean isJsonArray = true;
        try {
            JSONObject.parseObject(json);
            return true;
        } catch (Exception e) {
            isJsonObject = false;
            log.error("exception----------------"+e.getMessage());
        }
        try {
            JSONObject.parseArray(json);
        } catch (Exception e) {
            isJsonArray = false;
            log.error("exception----------------"+e.getMessage());
        }
        if(!isJsonObject && !isJsonArray){ //不是json格式
            return false;
        }
        return true;
    }
    /**
     * 上传文档到指定知识库
     *
     * @throws IOException 如果网络请求过程中发生I/O错误
     */
    public String UploadDocument(KmDoc kmDoc) throws IOException {
        String loginEndpoint = maxkbUrl + "/api/proxyapp/document/";
        //获取管理员token
        String token = loginAndGetToken(this.maxkbusername, this.maxkbuserpass, maxkbUrl);
        log.info("==========token==========" + token);
        // 创建URL对象
        URL url = new URL(loginEndpoint);
        // 打开连接
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        try {
            // 设置请求方法
            connection.setRequestMethod("POST");
            // 设置请求头信息
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("Accept", "*/*");
            connection.setRequestProperty("AUTHORIZATION", token);
            connection.setDoOutput(true);
            String jsonBody="{\n" +
                    "    \"data_type\": \"#data_type#\",\n" +
                    "    \"source_url\": \"#source_url#\",\n" +
                    "    \"document_name\": \"#document_name#\",\n" +
                    "    \"data\": \"#data#\",\n" +
                    "    \"role_name\": \"#role_name#\"\n" +
                    "}";

            String content=kmDoc.getContent().trim();
            if(kmDoc.getRemark()!=null && !kmDoc.getRemark().equals("")){
                content=kmDoc.getRemark().trim()+"\n"+content;
            }
            jsonBody=jsonBody.replaceAll("#data_type#","2");
            jsonBody=jsonBody.replaceAll("#source_url#",kmDoc.getId());
            jsonBody=jsonBody.replaceAll("#document_name#",kmDoc.getName());
            jsonBody=jsonBody.replaceAll("#data#",content);
            jsonBody=jsonBody.replaceAll("#role_name#",kmDoc.getKnowledgeBase());
            jsonBody = trimControlCharacter(jsonBody);
            log.info("=========指定body值========" + jsonBody);
            // 获取输出流并写入请求体
            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = jsonBody.getBytes(StandardCharsets.UTF_8);
                os.write(input, 0, input.length);
            }

            // 响应值
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // 用BufferedReader读取响应
                try (BufferedReader reader = new BufferedReader(
                        new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }
                    log.info("========赋予响应值========" + response);
                    // 将响应转换为JSON字符串
                    String jsonResponse = response.toString();
                    String code = new org.json.JSONObject(jsonResponse).optString("code", null);
                    log.info("========返回的结果========" + code);
                    return "";
                }
            } else {
                log.info("=====处理赋予响应=====" + responseCode);
                // 处理错误响应
                throw new IOException("Login failed with HTTP status: " + responseCode);
            }
        } finally {
            // 关闭连接
            if (connection != null)
                connection.disconnect();
        }
    }

}
